<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\StaffSignIn;
use addons\qingdongams\model\StaffSignInRead;
use think\Db;
use think\Exception;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 跟进签到
 */
class SignIn extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//获取跟进记录
	public function getList() {
        $params = $this->request->post();
		$relation_type = input('relation_type', '', 'intval');// customer客户 event 日程 workorder 业绩目标
		$relation_id   = input('relation_id', '', 'intval');
		$limit         = input("limit/d", 10);
		$is_read       = input('is_read', 0);//0 全部 1已读 2未读
		$staff_id = input('staff_id', 0);
		$customer_id = input('customer_id', 0);
        $createtime=input('createtime');
		$where         = [];
		if ($relation_type) {
			$where['relation_type'] = $relation_type;
			$where['relation_id']   = $relation_id;
		} 
		if ($staff_id) {
			$where['staff_id'] = $staff_id;
		}
        if ($createtime) {
            $times = setTimes($createtime, 'time');
            $where['createtime'] = ['between', $times];
        }

		if ($customer_id) {
			$where['customer_id'] = $customer_id;
		}
        if(empty($customer_id) && empty($relation_id) && empty($staff_id)){
            $where['staff_id'] = ['in', Staff::getMyStaffIds()];
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的创建
                    $where['owner_staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属创建
                    $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
                }
            }
        }
		$staff_id             = $this->auth->id;
		if ($is_read == 1) {//已读
			$ids         = StaffSignInRead::where(['staff_id' => $staff_id])->column('sign_in_id');
			$where['id'] = ['in', $ids];
		} elseif ($is_read == 2) {//未读
			$ids         = StaffSignInRead::where(['staff_id' => $staff_id])->column('sign_in_id');
			$where['id'] = ['not in', $ids];
		}
        if(isset($params['id_list'])){//日志 查询id列表
            $where=[];
            $where['id']=['in',explode(',',$params['id_list'])];
        }

		$records = StaffSignIn::where($where)->with([
			'staff',
			'customer',
			'read' => function ($query) use ($staff_id) {
				$query->where(['staff_id' => $staff_id]);
			},
            'comment_number',
            'workorder',
            'event_title',

		])->order('id desc')->paginate($limit)->toArray();

		$data = $records['data'];
		foreach ($data as $k => $v) {
			if (!empty($v['read'])) {
				$v['is_read'] = 1;
			} else {
				$v['is_read'] = 0;
			}
			if($v['relation_type'] == StaffSignIn::EVENT_TYPE){//日程
                unset($v['workorder']);
            }elseif($v['relation_type'] == StaffSignIn::WORKORDER_TYPE){//工单
                unset($v['event_title']);
            }else{
                unset($v['event_title']);
                unset($v['workorder']);
            }
			$data[$k] = $v;
		}
		$this->success('请求成功', [
			'total'        => $records['total'],
			'per_page'     => $records['per_page'],
			'current_page' => $records['current_page'],
			'last_page'    => $records['last_page'],
			'data'         => $data
		]);

		$this->success('请求成功', $records);
	}


	//创建
	public function createRecord() {
        $location = input('location');
        $lng = input('lng');
        $lat = input('lat');
        $file_ids = input('file_ids');
        $relation_process = input('relation_process');//跟进
        $customer_id = input('customer_id');
        $content = input('content');
        $relation_type = input('relation_type', '', 'trim');// customer客户 event 日程 workorder 工单
        $relation_id   = input('relation_id', '', 'intval');
        $reminds_id   = input('reminds_id');
        $next_time   = input('next_time',null);

        if (empty($lng) || empty($lat)) {
//            $this->error('地理位置不能为空');
        }
        if (empty($content)) {
            $this->error('签到备注不能为空');
        }
        if (empty($reminds_id)) {
            $this->error('提醒人不能为空');
        }

        $customer = Customer::where(['id' =>$customer_id])->find();
        if (empty($lng) && empty($lat)) {
            $distance = '';
        } elseif (empty($customer['lng']) && empty($customer['lat'])) {
            $distance = '';
        } else {
            $distance = getdistance($customer['lng'], $customer['lat'], $lng, $lat);
        }

        $data = [
            'staff_id' => $this->auth->id,
            'location' => $location,
            'lng' => $lng,
            'lat' => $lat,
            'file_ids' => $file_ids,
            'customer_id' => $customer_id,
            'relation_type' => $relation_type,//日程类型
            'relation_id' => $relation_id,//签到关联id
            'relation_process' => $relation_process,
            'customer_status' => $customer['contract_status'],//成交状态
            'content' => $content,
            'distance' => $distance,
            'next_time' => $next_time,
            'reminds_id' => $reminds_id,
        ];
		Db::startTrans();
		try {
			$result             = StaffSignIn::createSignIn($data);
            Customer::update(['last_time'=>$next_time],['id'=>$customer_id]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if ($result) {
			$this->success('新增跟进记录成功');
		}
	}


	//获取根据记录详情
	public function getDetail() {
		$id = input('id');
		if (empty($id)) {
			$this->error('参数不能为空');
		}
		$record =StaffSignIn::where(['id' => $id])->with([
			'staff',
			'customer'
		])->find();
		if (empty($record)) {
            //标记通知已读
            Message::setRead(Message::RECORD_TYPE, $id, $this->auth->id);
            Message::setRead(Message::SIGN_TYPE, $id, $this->auth->id);
			$this->error('记录已删除');
		}

		$reminds_id           = $record['reminds_id'];
		$reminds_id           = explode(',', $reminds_id);
		$names                = Staff::where(['id' => ['in', $reminds_id],'status'=>1])->column('name');
		$record['staff_name'] = implode(',', $names);

		//标记通知已读
		Message::setRead(Message::RECORD_TYPE, $id, $this->auth->id);
		Message::setRead(Message::SIGN_TYPE, $id, $this->auth->id);
		//添加阅读记录
		StaffSignInRead::addRead($id, $this->auth->id);

		$this->success('请求成功', $record);
	}

}
